const crypto = require('crypto');

module.exports = {
  main: async (event) => {
    // 1. 获取前端传递的URL并标准化
    let currentUrl = 'https://www.yunyakeji.top/';
    
    console.log("后端接收URL:", currentUrl); // 调试
    
    // 2. 获取access_token
    let tokenRes = await uniCloud.httpProxyForEip.get(
      `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8af91bdb35791866&secret=495dbbfadb8b253030660bd7b1b67988`
    );
    let { access_token = '' } = tokenRes.body;
    
    // 3. 获取jsapi_ticket (使用正确类型)
    const wxres = await uniCloud.httpProxyForEip.get(
      `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi` // 修复：type=jsapi
    );
    const ticket = wxres.body.ticket;
    
    // 4. 生成签名
    const noncestr = 'Wm3WZYTPz0wzccnW';
    const timestamp = Math.floor(Date.now() / 1000);
    
    // 关键：按照字典序排序的参数
    const str = `jsapi_ticket=${ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${currentUrl}`;
    
    console.log("签名字符串:", str); // 调试
    
    // 使用Node.js内置crypto模块
    const signature = crypto.createHash('sha1')
      .update(str)
      .digest('hex');
    
    // 5. 返回给前端
    return {
      code: 0,
      appId: 'wx8af91bdb35791866',
      timestamp,
      noncestr,
      signature,
      debug: {
        currentUrl,
        signatureStr: str,
        ticket
      }
    };
  }
}